package com.example.demo.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.example.demo.entity.SysRole;
import com.example.demo.entity.SysUser;
import com.example.demo.repository.SysUserRepository;
import com.example.demo.service.SysRoleService;

@Component
public class UserUtils {
	@Autowired
	private SysUserRepository userDAO;
	@Autowired
	private SysRoleService roleDAO;
	
	public SysUser getUser() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username=userDetails.getUsername();
		SysUser user=userDAO.findByUsername(username);
		return user;
	}
	

	public Boolean hasRole(String roleCode) {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<String> roleCodes=new ArrayList<>();
		String roles = getRoles();
		String[] strings = roles.split(",");
		for (String string : strings) {
			List<SysRole> sysRole3 = roleDAO.findByCode(string.replace(" ", ""));
			for (SysRole sysRole : sysRole3) {
				if(sysRole.getChildren()==null) {
					continue;
				}
				List<SysRole> children = sysRole.getChildren();
				for (SysRole sysRole2 : children) {
					roleCodes.add(sysRole2.getCode().replace(" ", ""));
				}				
			}
			roleCodes.add(string.replace(" ", ""));
		}
		return roleCodes.contains(roleCode);
	}
	
	public String getName() {
		User2 user2= (User2)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		return user2.getName();
	}
	public String getUsername() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username=userDetails.getUsername();
		return username;
	}
	
	public String getRoles() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String roles = userDetails.getAuthorities().toString();
		return roles.substring(1,roles.length()-1);
	}
}
